//
//  HUDWaitingAnimationView.swift
//  Browser
//
//  Created by 115 on 2017/3/3.
//  Copyright © 2017年 114la.com. All rights reserved.
//

import UIKit

class HUDWaitingAnimationView: UIImageView {

    static let shared = HUDWaitingAnimationView()
    
    fileprivate var imageView: UIImageView
    
    fileprivate var displayLink: CADisplayLink?

    fileprivate init() {
        self.imageView = UIImageView(image: UIImage(named: "hud_waiting_circle"))
        super.init(image: UIImage(named: "hud_waiting_logo"))
        self.addSubview(imageView)
        imageView.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
        }
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    deinit {
        
    }
    
    //调用了该方法后，需要确保结束时要调用stopAnimation()
    func startAnimation() -> HUDWaitingAnimationView {
        if self.displayLink != nil {//防止之前调用了start后忘记调用stop。
            self.displayLink?.invalidate()
            self.displayLink = nil
        }
        imageView.transform = CGAffineTransform.identity
        let displayLink = CADisplayLink(target: self, selector: #selector(HUDWaitingAnimationView.changeTransform))
        displayLink.add(to: RunLoop.main, forMode: RunLoop.Mode.default)
        
        self.displayLink = displayLink
        return self
    }
    
    func stopAnimation() {
        self.displayLink?.invalidate()
        self.displayLink = nil
    }
    
    @objc func changeTransform() {//根据帧率计算旋转角度
        let duration = displayLink?.duration ?? 0.016666667
        imageView.transform = imageView.transform.rotated(by: CGFloat(Double.pi * 2 * 2 * duration))
    }
    
}
